package com.west.imclient.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.west.imclient.view.LoginView;
import com.west.imclient.view.MeetingRoomView;

import imserverentity.entity.IChattable;
import imserverentity.entity.Protocol;
import imserverentity.entity.impl.Client;


public class LoginActionListener implements ActionListener{
	private LoginView loginView;
	public LoginActionListener(LoginView loginView) {
		this.loginView = loginView; 
	}

	public void actionPerformed(ActionEvent e) {
		try {
			Socket socket = new Socket("localhost", 8888);
			String account = loginView.getJtf().getText();
			IChattable client = new Client(account);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("from", client);
			Protocol protocol = new Protocol("login", params);
			System.out.println("Sender: " + protocol);
			
			OutputStream os = socket.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			InputStream is = socket.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			oos.writeObject(protocol);
			loginView.setVisible(false);
			new MeetingRoomView(ois, oos, client).setVisible(true);;
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
	}

}
